
//tslint:disable
import { Component, OnInit, Input, ViewChild, ChangeDetectorRef } from "@angular/core";
import { Router } from "@angular/router";

import { ModalController, AlertController, IonContent } from "@ionic/angular";
import { AppGlobalService } from "../../shared/service/app-global.service";
import { EventService } from "../../shared/service/event.service";
import { HttpService } from "../../shared/service/http.service";
import { IndexedDBService } from "../../shared/service/indexed-db.service";
import { RecommendModalComponent } from "../recommend-modal/recommend-modal.component";
import { ModalFromCenterLeave, ModalFromCenterEnter } from "src/app/utils/transitions";
import { ChatService } from "src/app/shared/service/chatService";
import { PageModalService } from "src/app/shared/service/page-modal-service";
import * as CryptoJS from 'crypto-js';
@Component({
  selector: "app-chat-invite",
  templateUrl: "./chat-invite.component.html",
  styleUrls: ["./chat-invite.component.scss"],
})
export class ChatInviteComponent implements OnInit {
  constructor(
    private modalCtrl: ModalController,
    private eventService: EventService,
    public router: Router,
    public alertController: AlertController,
    private appGlobalService: AppGlobalService,
    private chatService: ChatService,
    private indexedDBService: IndexedDBService,
    private pageModalService: PageModalService,
    private cd: ChangeDetectorRef,
    private http: HttpService
  ) {
    this.msgDatalist = [];
  }

  @Input() tagData: any;

  pageNo: any = 0;
  pageSize: any = 20;
  params: any;
  sessionId = localStorage.getItem("sessionId");
  currentJid = localStorage.getItem("userId");
  msgDatalist = [];
  ifLogin;
  notEsData: any;
  delayTime: 200;
  private timer: any;
  emptyHintLabel = '暂无数据';
  showEmptyHintLabel = true;
  ngOnInit() {
    let that = this;
    if (this.eventService.eventEmit.listenerCount('refreshChatInviteList') > 0) {
      this.eventService.eventEmit.removeListener('refreshChatInviteList');
    }
    // 2023.12.04 新增刷新邀约列表
    this.eventService.eventEmit.on("refreshChatInviteList", (obj) => {
      that.msgDatalist = [];
      that.initMyFriendList((responseDataList) => {
        that.appGlobalService.consoleLog('刷新我的好友列表', '');
        that.msgDatalist = responseDataList;
        that.cd.detectChanges();
      });
      // 2024.07.02 解决从聊天详情页面返回到好友列表获取聊天信息异常
    });



    // console.log('msg-----> ChatInviteComponent ngOnInit ' + new Date().getTime());
    this.msgDatalist = [];
    this.params = this.tagData.data.submit;
    this.notEsData = this.tagData.data.notEsData
      ? this.tagData.data.notEsData
      : false;
    this.ifLogin = localStorage.getItem("userId") !== "null";
    if (this.ifLogin) {
      if (!this.notEsData) {
        this.refreshUnReadChatList();
      } else {
        this.msgDatalist = this.initMyFriendList();
      }
    } else {
      this.msgDatalist = [];
    }

    // 判断是否已经注册事件过了如果已经注册过了 就不用再注册了
    if (
      this.eventService.eventEmit.listenerCount("refreshUnreadChatListMsg") > 0
    ) {
      this.eventService.eventEmit.removeListener("refreshUnreadChatListMsg");
    }
    this.eventService.eventEmit.on("refreshUnreadChatListMsg", (obj) => {
      // if (localStorage.getItem("refreshUnreadChatListMsgTag")) {
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        if (this.notEsData) {
          if (this.ifLogin) {
            // localStorage.removeItem("refreshUnreadChatListMsgTag");
            // this.refreshUnReadChatList();
            let parseObj = JSON.parse(obj);
            const tempObj = {
              msg: parseObj.msg,
              isNew: parseObj.isNew,
              updateTime: parseObj.updateTime,
              datetime: parseObj.datetime,
              id: parseObj.key,
              number: parseObj.number,
              nickname: obj.toUserName ? obj.toUserName : "",
              avatar_url: obj.toUserIcon ? obj.toUserIcon : "",
              fromUserMobile: obj.fromUserMobile ? obj.fromUserMobile : "",
              toUserIcon: obj.toUserIcon ? obj.toUserIcon : "",
              toUserName: obj.toUserName ? obj.toUserName : "",
              key: parseObj.key
            };
            const currentJidIndex = String(parseObj.key).indexOf(this.currentJid);
            if (currentJidIndex >= 0) {
              if (parseObj.toUserName) {
                tempObj.nickname = parseObj.toUserName;
                tempObj.avatar_url = parseObj.toUserIcon;
                tempObj.fromUserMobile = parseObj.fromUserMobile;
                tempObj.key = parseObj.key;
              } else {
                let senderId;
                if (currentJidIndex > 24) {
                  senderId = String(parseObj.key).split("-")[0];
                } else {
                  senderId = String(parseObj.key).split("-")[1];
                }
                this.indexedDBService.getByKey(
                  senderId,
                  "user",
                  (userData) => {
                    userData.onsuccess = async (userEvent) => {
                      if (userData.result) {
                        const userObj = userData.result;
                        tempObj.nickname = userObj.nickname;
                        tempObj.avatar_url = userObj.avatar_url;
                      } else {
                        // tempObj.nickname = '昵称';
                        // tempObj.avatar_url = 'assets/icon/IM_customer service@3x.png';
                        this.http.get(
                          "message/userinfo/im/" + senderId,
                          (response) => {
                            const data = response.data;
                            if (senderId.includes('random')) {
                              tempObj.nickname = '访客';
                              data.nickname = tempObj.nickname;
                            } else {
                              tempObj.nickname = data.nickname;
                            }
                            tempObj.avatar_url = data.avatar_url;
                            this.indexedDBService.add(data, senderId, "user");
                          },
                          (error) => {
                            console.log(
                              "msg-----> error:" + JSON.stringify(error)
                            );
                          }
                        );
                      }
                    };
                  }
                );
              }
            }
            let isNew = true;
            try {
              this.msgDatalist.forEach(element => {
                if (element.id === parseObj.key) {
                  isNew = false;
                  element.msg = tempObj.msg;
                  element.isNew = tempObj.isNew;
                  element.updateTime = tempObj.updateTime;
                  element.datetime = tempObj.datetime;
                  element.number += 1;
                  tempObj.number = element.number;
                  if (parseObj.fromUserMobile) {
                    tempObj.fromUserMobile = parseObj.fromUserMobile;
                  }
                  if (parseObj.toUserIcon) {
                    tempObj.toUserIcon = parseObj.toUserIcon;
                  }
                  if (parseObj.toUserName) {
                    tempObj.toUserName = parseObj.toUserName;
                  }
                  if (parseObj.key) {
                    tempObj.key = parseObj.key;
                  }
                  throw new Error('break');
                }
              });
            } catch (error) {
              if (error.message !== "break") { throw error; }
            }
            if (isNew) {
              if (tempObj.id !== undefined) {
                this.msgDatalist.push(tempObj);
                this.indexedDBService.putByKeyCallbak(
                  tempObj,
                  tempObj.id,
                  "unreadchat",
                  () => {
                    console.log('unreadChat添加成功!');
                  });
              }
            }

          }
        } else {
          this.msgDatalist = this.tagData.data.data;
          // console.log(this.msgDatalist, "msgggshssssss");
        }
      }, 300);

      // }
    });
  }

  async countNumAndUpdate() {
    const that = this;
    const unReadDataList = [];
    // const unReadNum;
    await this.indexedDBService.getAllValues("unreadNum", (obj) => {
      obj.onsuccess = async (event) => {
        const cursor = event.target.result;
        let temp;
        if (cursor) {
          temp = String(cursor.key).substring(0, 49);
          // localStorage.setItem(temp, '');
          // unReadDataList.push(cursor.key);
          cursor.continue();
        } else {
          console.log(JSON.stringify(unReadDataList));
          console.log("msg-----> read complete.");
          // 统计完成马上更新表
        }
      };
    });
  }
  refreshUnReadChatList() {
    const that = this;
    // that.msgDatalist = [];
    const tempMsgDatalist = [];
    if (that.msgDatalist && that.msgDatalist.length > 0) {
      return;
    }
    let swichTime = "";
    try {
      this.indexedDBService.getAllValues("unreadchat", (obj) => {
        obj.onsuccess = (event) => {
          const cursor = event.target.result;
          const tempObj = {
            msg: { message: "" },
            isNew: 0,
            updateTime: "",
            datetime: "",
            id: "",
            number: 0,
            nickname: "",
            avatar_url: "",
            fromUserMobile: "",
          };
          if (cursor) {
            const currentJidIndex = String(cursor.key).indexOf(this.currentJid);
            if (currentJidIndex >= 0) {
              const parseObj = cursor.value;
              tempObj.msg = parseObj.msg;
              tempObj.datetime = parseObj.datetime;
              tempObj.id = cursor.key;
              tempObj.isNew = parseObj.isNew;
              tempObj.updateTime = parseObj.updateTime;
              let senderId;
              if (currentJidIndex > 24) {
                senderId = String(cursor.key).split("-")[0];
              } else {
                senderId = String(cursor.key).split("-")[1];
              }
              if (parseObj.fromUserMobile) {
                tempObj.fromUserMobile = parseObj.fromUserMobile;
              }
              if (parseObj.toUserName) {
                tempObj.nickname = parseObj.toUserName;
                tempObj.avatar_url = parseObj.toUserIcon;
              } else {
                this.indexedDBService.getByKey(
                  senderId,
                  "user",
                  (userData) => {
                    userData.onsuccess = async (userEvent) => {
                      if (userData.result) {
                        const userObj = userData.result;
                        tempObj.nickname = userObj.nickname;
                        tempObj.avatar_url = userObj.avatar_url;
                      } else {
                        // tempObj.nickname = '昵称';
                        // tempObj.avatar_url = 'assets/icon/IM_customer service@3x.png';
                        this.http.get(
                          "message/userinfo/im/" + senderId,
                          (response) => {
                            const data = response.data;
                            if (senderId.includes('random')) {
                              tempObj.nickname = '访客';
                              data.nickname = tempObj.nickname;
                            } else {
                              tempObj.nickname = data.nickname;
                            }
                            tempObj.avatar_url = data.avatar_url;
                            this.indexedDBService.add(data, senderId, "user");
                          },
                          (error) => {
                            console.log(
                              "msg-----> error:" + JSON.stringify(error)
                            );
                          }
                        );
                      }
                    };
                  }
                );
              }

              tempObj.number = parseObj.number;
              if (swichTime === "") {
                swichTime = tempObj.updateTime;
                tempMsgDatalist.unshift(tempObj);
              } else if (tempObj.updateTime > swichTime) {
                swichTime = tempObj.updateTime;
                tempMsgDatalist.unshift(tempObj);
              } else {
                tempMsgDatalist.push(tempObj);
              }
            }
            cursor.continue();
          } else {
            that.msgDatalist = tempMsgDatalist;
          }
        };
        obj.onerror = (event) => {
          // console.log('msg----> ChatInviteComponent getAllValues error');
        };
      });
    } catch (error) {
      console.log("msg----> ChatInviteComponent getAllValues error");
    }
  }



  // 2024.07.03 重构 
  openModal(item) {
    // 2023.12.01 消息红点状态还是要及时更新
    const that = this;
    const targetUserId = item.friendNo;
    // tslint:disable-next-line:no-string-literal
    item['groupNo'] = targetUserId;
    item.isNew = false;
    item.badge = 0;
    if (!item.id
      && item.link
      && item.link.params
      && item.link.params.imId) {
      item.id = item.link.params.imId + '-' + localStorage.getItem('userId');
    }
    item.type = that.appGlobalService.clientType;
    // 如果是从成交记录进入的则需要添加类型区分
    if (localStorage.getItem('currentPath')) {
      item['currentPath'] = localStorage.getItem('currentPath');
    }
    localStorage.setItem("chatPageFrom", "invite");
    if (item.groupNo) {
      this.chatService.enterTheChatRoomUseUserId = item.groupNo;
      this.chatService.currentGroupName = item.friendName?item.friendName:item.groupName;
    }
    localStorage.setItem('enterChatRoomByUserId', '1');
    this.eventService.eventEmit.emit('enterChatRoomByUserId',
      {
        userId: item.groupNo,
        fromFriendList: true,
        friendName: item.friendName,
        friendAvatar: item.friendAvatar
      }
    );
  }

  async callConsultantNow(data) {
    console.log("专属顾问", data);
    const alert = await this.alertController.create({
      header: "",
      subHeader: "",
      message: data.username + " " + data.mobile,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary",
          handler: (blah) => {
            console.log("取消");
          },
        },
        {
          text: "拨打",
          handler: () => {
            this.http.changeCallNumber(data.mobile);
          },
        },
      ],
    });
    await alert.present();
  }

  async call(name, phone) {
    try {
      if (!name) { name = ""; }
      if (!phone) { return; }
      const alert = await this.alertController.create({
        header: "",
        subHeader: "",
        message: name + " " + phone,
        buttons: [
          {
            text: "取消",
            role: "cancel",
            cssClass: "secondary",
            handler: (blah) => {
              console.log("取消");
            },
          },
          {
            text: "拨打",
            handler: () => {
              this.http.changeCallNumber(phone);
            },
          },
        ],
      });
      await alert.present();
    } catch (error) {

    }
    // console.log("专属顾问", data);

  }



  go(item) {
    event.stopPropagation();
    if (!item) {
      return;
    }
    // 已经购买直接刷新页面
    if (item.submit) {
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: this.sessionId,
      };
      this.http.post("application/submit", params, (res) => {
        // 请求数据成功
        if (res.success === true) {
          this.appGlobalService.showToast(res.message, 2000, "middle");
          this.appGlobalService.reloadCurrentPage();
        } else {
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, "middle");
        }
      });
    } else if (item.link.type && item.link.type === "model") {
      // 未收费
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: item.link.target,
        params: item.link.params,
      };
      this.http.post("application/page", params, (res) => {
        console.log(JSON.parse(res.script));
        const tmpData = JSON.parse(res.script).views[0].tags[0].data;
        this.showRecommenMessageVip(tmpData);
      });
    }
  }
  // 购买信息 开通会员
  async showRecommenMessageVip(vipData) {
    const modal = await this.modalCtrl.create({
      showBackdrop: true,
      cssClass: "recommend-modal-auto-heigth",
      component: RecommendModalComponent,
      componentProps: { vipData },
      leaveAnimation: ModalFromCenterLeave,
      enterAnimation: ModalFromCenterEnter
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
  }
  ngOnDestroy(): void {
    this.eventService.removeCustomListListenersByName('refreshUnreadChatListMsg');
  }


  // 下拉重新获取列表
  loadGroupList(event) {
    if (event) {
      event.stopPropagation();
    }
    this.msgDatalist = [];
    this.msgDatalist = this.initMyFriendList();
    event.target.complete();
  }

  // 初始化好友列表
  initMyFriendList(callbackFunc?) {
    let useId = localStorage.getItem('userId');
    let tempMsgDataList = [];
    const url = this.http.talkQueryFriendsList + this.chatService.getPaginationParamStr(useId, this.pageSize, this.pageNo);
    this.pageModalService.getGetData(url, (response) => {
      if (response) {
        const data = JSON.parse(response);
        if (data
          && data.listData !== undefined
          && data.listData.length > 0
        ) {
           // tslint:disable-next-line:prefer-for-of
           for (let index = 0; index < data.listData.length; index++) {
            const element = data.listData[index];
            if (element.hasNoRead) {
              this.chatService.unreadFriendList.add(element.friendNo);
            }
          }
          setTimeout(() => {
            this.chatService.setMyFriendData(data);
          }, 200);

          // const tempList = data.listData;
          // if (tempList && tempList.length > 0) {
          //   for (let index = 0; index < tempList.length; index++) {
          //     const ele = tempList[index];
          //     if (ele) {
          //       tempMsgDataList.push(this.chatService.getProcessSingleMsg(useId, ele));
          //     }
          //   }
          if (callbackFunc) {
            callbackFunc(tempMsgDataList)
          }
          // }
        }
      }
    });
    return tempMsgDataList;
  }

  // 好友列表分页
  loadData(event) {
    const that = this;
    that.showEmptyHintLabel = that.msgDatalist.length === 0;
    if (that.msgDatalist.length > 0) {
      that.pageNo += 1;
    } else {
      that.pageNo = 0;
    }
    setTimeout(() => {
      let uid = localStorage.getItem('userId');
      const url = this.http.talkQueryFriendsList + this.chatService.getPaginationParamStr(uid, this.pageSize, this.pageNo);
      this.pageModalService.getGetData(url, (response) => {
        if (response) {
          try {
            const data = JSON.parse(response);
            if (data && data.listData && data.listData.length > 0) {
              this.pageModalService.chatService.setMyFriendData(data);
              // data.listData.forEach((ele) => {
              //   if (ele) {
              //     that.msgDatalist.push(that.chatService.getProcessSingleMsg(uid, ele));
              //   }
              // });
              event.target.complete();
            } else {
              that.showEmptyHintLabel = true;
              that.pageNo -= 1;
              that.appGlobalService.consoleLog('没有更多数据了！', '');
              event.target.complete();
            }
          } catch (e) {
            that.appGlobalService.consoleLog('解析响应数据时出错:', e);
            event.target.complete();
          }
        }
      });
    }, 200);
  }
}
